<?php
// +----------------------------------------------------------------------
// | 后台用户管理
// +----------------------------------------------------------------------
namespace app\common\service;
use base\files\Poster;
use app\common\event\CouponUser as CouponUserEvent;
use think\facade\Session;
use think\Db;

class Coupon 
{

	/**
	* 错误信息
	*/
	public  $errorInfo;
	
	/**
	* 优惠券发放
	* @param  $cids  			必填 		优惠券id,多个逗号分割 
	* @param  $uids   		必填 		用户id，按指定用户发放
	* @param  $is_give   	选填 		是否赠送券，1是，0不是
	* @param  $get_mode 选填 		发放类型
	*/
	public function grant($cids,$uids="",$is_give=0,$get_mode='receive'){
		
		//获取模型
		$coupon = model("coupon");
		//获取事务模型
		$coupon_db = $coupon->db(false);
		//开启事务
		$coupon_db->startTrans();
	
		try {
			
			//查询用户数量
			$userIds = model('user')->where('id','in',$uids)->column('id');
			
			//判断用户数量
			if( count($userIds) == 0){
				$coupon_db->rollback();
				$this->errorInfo = "当前条件所发放的用户数量为0，发放失败！";
				return false;
			}
			
			//查询优惠券 
			$subQuery = model('coupon_user')
			    ->field('coupon_id,count(id) as receive_num')
				->group("coupon_id")
				->where("uid",'in',$userIds)
			    ->buildSql();
			$coup =  $coupon->alias('a')
				->leftJoin("$subQuery b",'a.id = b.coupon_id')
				->lock(true)
				->field('a.*')
				->field('ifnull(b.receive_num,0) as receive_num')
				->where('a.id','in',$cids)
				->select();

			//判断优惠券是否存在
			if( count($coup) < 1 ){
				$this->errorInfo = "优惠券不存在！";
				return false;
			}
			
			// 判断优惠券数量
			foreach ($coup as $key => $itme) {
				if(count($userIds) > $itme['remain_count']){
					$this->errorInfo ='【'.$itme['coupon_name']."】剩余数量不足发放！";
					return false;
				}
				if( $itme['stop_time'] <= date('Y-m-d') ){
					$this->errorInfo = '【'.$itme['coupon_name']."】已过期，不能发放！";
					return false;
				}
				if( $itme['can_count'] <=  $itme['receive_num'] ){
					$this->errorInfo = '【'.$itme['coupon_name']."】已达到可领取数，不能再次领取！";
					return false;
				}
			}
				
			//更新优惠券数量
			if( $coupon_db->where("id",'in',$cids)->setDec('remain_count', count($userIds) ) == 0){
				$this->errorInfo = "发送错误 , 更新优惠券数量失败！";
				return false;
			}
			
			//发放
			$list = [];
			foreach ($coup as $k => $itme) {
				$stop_time = ($itme['can_day'] ?: 1000) - 1;
				foreach ($userIds as $key => $id) {
					$list[] = [
						'uid'=>$id,
						'shop_id' => $itme['shop_id'],
						'goods_id' => $itme['goods_id'],
						'coupon_id' => $itme['id'],
						'coupon_price' =>  $itme['coupon_price'],
						'coupon_name' => $itme['coupon_name'],
						'start_time' => date('Y-m-d'),
						'stop_time' => date("Y-m-d",strtotime("+$stop_time  day")),
						'use_min_price' => $itme['use_min_price'],
						'can_count' => $itme['can_count'],
						'remark' => $itme['remark'],
						'can_day' =>$itme['can_day'],
						'get_mode' => $get_mode,
						'is_give' => $is_give,
						'full_cond_reduce' => $itme['full_cond_reduce'],
						'fracture' => $itme['fracture']
					];
				};
			}
			
			//发放
			if( !model('CouponUser')->saveAll($list) ){
				$coupon_db->rollback();
				$this->errorInfo = "发送失败！";
				return false;
			}
			
			//提交事务
			$coupon_db->commit();
			return  true;		
			
		} catch (\Exception $e) {
			$coupon_db->rollback();
			return false;
		}
		
	}
	
	
}

